package com.hmall.search.web;

import com.alibaba.fastjson.JSON;
import com.hmall.common.dto.PageDTO;
import com.hmall.search.pojo.ItemDto;
import com.hmall.search.pojo.RequestParams;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 查找控制类
 *
 * @Author Json.D
 * @Date 2022/8/11 11:20
 * @Blog
 * @Description: 查找控制类
 */
@Slf4j
@RestController
@RequestMapping("search")
public class SearchController {

    @Autowired
    private RestHighLevelClient client;

    /**
     * 自动填充功能
     *
     * @param key
     * @return
     */
    @GetMapping("suggestion")
    public List<String> getSuggestion(@RequestParam("key") String key) {
        log.info("传来的key为：{}", key);
        try {
            //准备request对象
            SearchRequest request = new SearchRequest("item");
            //准备suggest查询条件
            request.source().suggest(new SuggestBuilder()
                    //创建对象，取名
                    .addSuggestion("mySuggestion",
                            //SuggestBuilders，后面加查询条件
                            SuggestBuilders.completionSuggestion("suggestion")
                                    .prefix(key)
                                    .size(10)
                                    .skipDuplicates(true)));
            //处理结果
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            List<String> list = new ArrayList<>();
            //根据名称获取补全数据结果
            CompletionSuggestion mySuggestion
                    = response.getSuggest().getSuggestion("mySuggestion");
            //获取options并遍历
            List<CompletionSuggestion.Entry.Option> options = mySuggestion.getOptions();
            for (CompletionSuggestion.Entry.Option option : options) {
                //获取一个option中的text，也就是补全的词条
                String string = option.getText().toString();
                list.add(string);
            }
            return list;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new ArrayList<>();
    }

    @PostMapping("filters")
    public Map<String, List<String>> filters(@RequestBody RequestParams params) {

        try {
            SearchRequest request = new SearchRequest("item");
            // 2.准备DSL
            // 2.1.不要文档数据
            request.source().size(0);
            buildBasicQuery(params, request);

            request.source().aggregation(
                    AggregationBuilders.terms("brandAgg").field("brand").size(20)
            );
            request.source().aggregation(
                    AggregationBuilders.terms("categoryAgg").field("category").size(20)
            );

            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            Map<String, List<String>> map = new HashMap<>(2);

            Aggregations aggregations = response.getAggregations();
            //4，1根据名称获得品牌聚合
            Terms brandAgg = aggregations.get("brandAgg");
            List<String> brandList = new ArrayList<>();
            for (Terms.Bucket bucket : brandAgg.getBuckets()) {
                String keyAsString = bucket.getKeyAsString();
                brandList.add(keyAsString);
            }
            map.put("brand", brandList);

            //4，1根据名称获得分类聚合
            Terms categoryAgg = aggregations.get("categoryAgg");
            List<String> categoryList = new ArrayList<>();
            for (Terms.Bucket bucket : categoryAgg.getBuckets()) {
                String keyAsString = bucket.getKeyAsString();
                categoryList.add(keyAsString);
            }
            map.put("category", categoryList);
            return map;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new HashMap<>();
    }

    @PostMapping("list")
    public PageDTO<ItemDto> list(@RequestBody RequestParams params) {
        long value = 0;
        List<ItemDto> list = null;
        try {
            SearchRequest request = new SearchRequest("item");

            buildBasicQuery(params, request);

            Integer size = params.getSize();
            Integer page = params.getPage();
            request.source().from((page - 1) * size).size(size);

            // 2.3.排序
            String sortBy = params.getSortBy();
            if ("sold".equals(sortBy)) {
                request.source().sort(sortBy, SortOrder.DESC);
            } else if ("price".equals(sortBy)) {
                request.source().sort(sortBy, SortOrder.ASC);
            }
            // 2.4.高亮
            request.source().highlighter(new HighlightBuilder().field("name").requireFieldMatch(false));


            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            value = response.getHits().getTotalHits().value;

            list = new ArrayList<>();
            SearchHit[] hits = response.getHits().getHits();
            for (SearchHit hit : hits) {
                String sourceAsString = hit.getSourceAsString();
                ItemDto itemDto = JSON.parseObject(sourceAsString, ItemDto.class);

                // 4.6.获取高亮
                Map<String, HighlightField> map = hit.getHighlightFields();
                if (map != null && map.size() > 0) {
                    HighlightField field = map.get("name");
                    String name = field.getFragments()[0].string();
                    itemDto.setName(name);
                }

                list.add(itemDto);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        PageDTO<ItemDto> pageDTO = new PageDTO<>();
        pageDTO.setList(list);
        pageDTO.setTotal(value);
        return pageDTO;

    }

    /**
     * 查询条件
     *
     * @param params
     * @param request
     */
    private void buildBasicQuery(@RequestBody RequestParams params, SearchRequest request) {
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        //1,1 key
        String key = params.getKey();
        if (StringUtils.isNotBlank(key)) {
            boolQueryBuilder.must(QueryBuilders.matchQuery("all", key));
        } else {
            boolQueryBuilder.must(QueryBuilders.matchAllQuery());
        }

//            request.source().from(params.getPage())
//                    .size(params.getSize());
        //1,2brand
        String brand = params.getBrand();
        if (StringUtils.isNotBlank(brand)) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("brand", brand));
        }
        //1,3category
        String category = params.getCategory();
        if (StringUtils.isNotBlank(category)) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("category", category));
        }

        //1,4 price
        Long maxPrice = params.getMaxPrice();
        Long minPrice = params.getMinPrice();
        if (maxPrice != null && minPrice != null) {
            boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").
                    gte(minPrice * 100).lte(maxPrice * 100));
        }
        FunctionScoreQueryBuilder functionScoreQuery =
                QueryBuilders.functionScoreQuery(
                        // 原始查询，相关性算分的查询
                        boolQueryBuilder,
                        // function score的数组
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                                // 其中的一个function score 元素
                                new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                        // 过滤条件
                                        QueryBuilders.termQuery("isAD", true),
                                        // 算分函数
                                        ScoreFunctionBuilders.weightFactorFunction(10)
                                )
                        });
        request.source().query(functionScoreQuery);
    }
}
